package sy.controller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import sy.model.*;
import sy.pageModel.DataGrid;
import sy.pageModel.Json;
import sy.pageModel.Mgif;
import sy.pageModel.Mreach;
import sy.pageModel.Mtaskrecord;
import sy.pageModel.PageHelper;
import sy.pageModel.SessionInfo;
import sy.pageModel.User;
import sy.service.*;
import sy.util.ConfigUtil;
import sy.util.IpUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 用户控制器
 * 
 * @author 孙宇
 * 
 */
@Controller
@RequestMapping("/treachController")
public class TreachController extends BaseController {

    @Autowired
    private UserServiceI userService;
	@Autowired
	private ReachServiceI reachService;
	
	@Autowired
	private TaskRecordServiceI taskrecordService;
	
	@Autowired
	private UserController usercontrol;
	
	@Autowired
	private TaskTypeServiceI   taskTypeService;

    @Autowired
    private InviteServiceI inviteService;
	/**
	 * 签到处理
	 * 
	 * @param id
	 * 
	 */
	@ResponseBody
	@RequestMapping("/addreach")
	public String addtaskrecord(HttpSession session,HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		JSONObject jsobj = new JSONObject();
		SessionInfo sessionInfo = (SessionInfo)session.getAttribute(ConfigUtil.getSessionInfoName());
		if(sessionInfo == null){
			jsobj.put("status", -1);
			jsobj.put("msg", "登录超时");
		}else{
			try {
				Date currentTime = new Date();
				SimpleDateFormat formatterstr = new SimpleDateFormat("MM-dd HH:mm");
			    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			    Date dateString =formatter.parse(formatter.format(currentTime));
				int count = taskrecordService.getexistday(sessionInfo.getUserid(), dateString);													//查询用户是否当天签到
				if(count==0){
					Mtaskrecord  task = new Mtaskrecord();
					task.setTaskType("3");							//设置类型
					task.setUserid(sessionInfo.getUserid());		//设置用户id
					Integer score = taskTypeService.gettasktype("3").getScore();
					task.setScore(score);							//设置积分
					task.setDisplaytime(formatterstr.format(currentTime));
					taskrecordService.add(task);
					usercontrol.updatetotalscore(sessionInfo.getId(), score, 1);//更新积分
					int reachcount  = taskrecordService.checklevl(sessionInfo.getUserid());
					int levnow 		= reachcount/3+1;					//签到升级算法
					usercontrol.updatelevl(sessionInfo.getId(), levnow);//执行升级的过程
					jsobj.put("status", 1);
					jsobj.put("msg", score);

                    //三级分成

                    getMoenyTo(score,sessionInfo);

				}else{
					jsobj.put("status", 0);
					jsobj.put("msg", "你今天已签到咯!");
				}
			} catch (Exception e) {
				e.printStackTrace();
				jsobj.put("status", 0);
				jsobj.put("msg", "系统错误");
			}
		}
		
		return jsobj.toJSONString();
	}
    //userid:邀请人id inviteuserid：被邀请人id 获得被邀请人的所有父级邀请人id 向上面找三级
    public List<Tinviterecord> getTGClass(String userid)throws Exception{

        List<Tinviterecord> tinviterecords=new ArrayList<Tinviterecord>();

        Tinviterecord tinviterecord1=null;
        Tinviterecord tinviterecord2=null;
        Tinviterecord tinviterecord3=null;
        //如果不为空表示存在上级推广  第一级
        tinviterecord1=inviteService.getUpClass(userid);

        if(tinviterecord1!=null){
            tinviterecords.add(tinviterecord1);
            //找第二级
            tinviterecord2= inviteService.getUpClass(tinviterecord1.getUserid());
            if(tinviterecord2!=null){
                tinviterecords.add(tinviterecord2);
                //找第三级
                tinviterecord3= inviteService.getUpClass(tinviterecord2.getUserid());
                if(tinviterecord3!=null){
                    tinviterecords.add(tinviterecord3);
                }
            }

        }

        return tinviterecords;
    }
    //三级分成
    public void getMoenyTo(Integer pub,SessionInfo sessionInfo){
        try{
            //定义三级推广用户所加积分变量
            long gold1=0;

            Tinviterecord tinviterecord=inviteService.getUpClass(sessionInfo.getUserid()+"");
            if(tinviterecord!=null){//改用户是被邀请  第一次做人要 7W
                //判断是否第一次做任务
                List<Taskrecord> taskrecords= taskrecordService.gettask(sessionInfo.getUserid());
                if(taskrecords.size()<=0){//第一次做任务
                    gold1+=70000;

                }
                //获得这个用户推广向上三级 用户
                List<Tinviterecord> tinviterecords= getTGClass(sessionInfo.getUserid()+"");
                long gold=0;
                for(int i=0;i<tinviterecords.size();i++){
                    Tuser u = null;
                    User user = new User();
                    if(i==0){
                        u=userService.getUserByUserId(tinviterecords.get(i).getUserid());
                        double t= pub*0.35;
                        gold= (long)t+gold1;//加上第一次做任务积分 没有加0

                        user.setId(u.getId());
                        user.setTotalscore(u.getTotalscore()+(int)gold);
                        user.setUnchangedscore(u.getUnchangedscore()+(int)gold);
                        userService.editotlescore(user);

                        //     usercontrol.updatetotalscore(u.getId(),(int)gold , 1);//更新积分

                    }else if(i==1){
                        u=userService.getUserByUserId(tinviterecords.get(i).getUserid());
                        double t= pub*0.1;

                        user.setId(u.getId());
                        user.setTotalscore(u.getTotalscore()+(int)t);
                        user.setUnchangedscore(u.getUnchangedscore()+(int)t);
                        userService.editotlescore(user);

                    }else if(i==2){
                        u=userService.getUserByUserId(tinviterecords.get(i).getUserid());
                        double t= pub*0.05;
                        user.setId(u.getId());
                        user.setTotalscore(u.getTotalscore()+(int)t);
                        user.setUnchangedscore(u.getUnchangedscore()+(int)t);
                        userService.editotlescore(user);

                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
	 * 签到天数和等级
	 * 
	 * @param id
	 * 
	 */
	@ResponseBody
	@RequestMapping("/queryreach")
	public String que(HttpSession session) {
		JSONObject jsobj = new JSONObject();
		JSONObject jsobjzj = new JSONObject();
		SessionInfo sessionInfo = (SessionInfo)session.getAttribute(ConfigUtil.getSessionInfoName());
		if(sessionInfo == null){
			jsobj.put("status", -1);
			jsobj.put("msg", "登录超时");
		}else{
			try {
				int reachcount  = taskrecordService.checklevl(sessionInfo.getUserid());
				int levnow 		= reachcount/3+1;	
				jsobjzj.put("daycount", reachcount);
				jsobjzj.put("lev", levnow);
				jsobj.put("status", 1);
				jsobj.put("msg", jsobjzj);
			} catch (Exception e) {
				e.printStackTrace();
				jsobj.put("status", 0);
				jsobj.put("msg", "系统错误");
			}
		}
		return jsobj.toJSONString();
	}
	
}
